package utils;

import config.PathConfig;
import entity.*;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * describe 文件工具类
 * author wencong 2022/3/3
 */
public class FileUtil {

    /**
     * 生成文件存放路径，初始化
     */
    public static String depositFilePath(ProjectEntity projectEntity, String path, String ctimeStr) {
        // 项目存放目录为空时，设置默认存放目录
        if (StringUtils.isBlank(path)) {
            path = PathConfig.depositFilePath + File.separator + projectEntity.getLanguage()
                    + File.separator + projectEntity.getProjectName()
                    + File.separator + ctimeStr;
        }
        mkdirFile(path);
        return path;
    }

    /** vm文件存放路径， 项目内用相对路径 */
    public static String vmFilePath(String vmFileName, ProjectEntity projectEntity) {
        return projectEntity.getVmPath() + File.separator + vmFileName;
    }

    /** vm文件路径加文件名，文件名加上vm名 */
    public static String targetFile(ProjectEntity projectEntity, TableEntity tableEntity, String vmFileName, Map<String, String[]> velocityMap, String ctimeStr) {
        String depositFilePath = depositFilePath(projectEntity, velocityMap.get(vmFileName)[3], ctimeStr);
        String filePath;
        if (StringUtils.isBlank(velocityMap.get(vmFileName)[3])) {
            return depositFilePath + File.separator + tableEntity.getClassName() + velocityMap.get(vmFileName)[1] + velocityMap.get(vmFileName)[2];
        } else if (vmFileName.equals("Services.vm") || vmFileName.equals("Views.vm")) {
            filePath = depositFilePath + File.separator + tableEntity.getModular() + File.separator + velocityMap.get(vmFileName)[0];
        } else {
            filePath = depositFilePath + File.separator + velocityMap.get(vmFileName)[0] + File.separator + tableEntity.getModular();
        }
        mkdirFile(filePath);
        // 文件名
        String fileName;
        if (vmFileName.equals("Entity.vm")) {
            fileName = tableEntity.getClassName();
        } else if (vmFileName.equals("Services.vm") || vmFileName.equals("Views.vm")) {
            fileName = tableEntity.getRoute();
        } else {
            fileName = tableEntity.getClassName() + velocityMap.get(vmFileName)[1];
        }
        return filePath + File.separator + fileName + velocityMap.get(vmFileName)[2];
    }

    /**
     * 创建多级存储文件夹
     */
    public static void mkdirFile(String filePath) {
        File folder = new File(filePath);
        try {
            if (!folder.exists() && !folder.isDirectory()) {
                if (!folder.mkdirs()) {
                    throw new IOException("创建文件夹失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入文件
     */
    public static void writer(String stringWriter, String targetFile) {
        FileWriter writer;
        try {
            // 字符串写入文件
            writer = new FileWriter(targetFile);
            writer.write(stringWriter);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writerSql(String[] tableNamesStatic, String[] vmFileNamesStatic, DatebaseEntity datebaseEntity,ProjectEntity projectEntity, String ctimeStr,Map<String, String> typeMap){
        boolean bool = false;
        for (String str : vmFileNamesStatic){
            if (str.equals("Sql.vm")){
                bool = true;
                break;
            }
        }
        if (bool){
            String targetFile = depositFilePath(projectEntity, null, ctimeStr) + "/Sql.sql";
            Map<String, Object> replaceMap = new HashMap<>();
            int menuLastId = MysqlUtils.lastId(datebaseEntity, "ums_menu");
            int resourceLastId = MysqlUtils.lastId(datebaseEntity, "ums_resource");
            List<MenuEntity> menuEntityList = new ArrayList<>();
            List<ResourceEntity> resourceEntityList = new ArrayList<>();

            String[] resourceUrlStrs = {"page","list","info","insert","delete","update"};
            String[] resourceWebStrs = {"分页","列表","详情","新增","删除","修改"};
            String menuName = "";
            int menuPid = 0;
            for(String tableName: tableNamesStatic){
                TableEntity tableEntity = MysqlUtils.getTable(datebaseEntity, tableName, typeMap);
                String menuNameNew = tableEntity.getModular()+"管理";
                if (!menuName.equals(menuNameNew)){
                    menuName = menuNameNew;
                    menuPid = MysqlUtils.tableId(datebaseEntity, "ums_menu", menuName);
                    if (menuPid == 0){ // 没有上级菜单
                        menuLastId = menuLastId + 1;
                        MenuEntity menuEntity = new MenuEntity();
                        menuEntity.setMenuId(menuLastId);
                        menuEntity.setMenuPid(0);
                        menuEntity.setMenuType(0);
                        menuEntity.setMenuName(tableEntity.getModular()+"管理");
                        menuEntity.setMenuRouter("");
                        menuEntity.setMenuViewPath("");
                        menuEntityList.add(menuEntity);
                        menuPid = menuLastId;
                    }
                }
                MenuEntity menuEntity = new MenuEntity();
                menuLastId = menuLastId + 1;
                menuEntity.setMenuId(menuLastId);
                menuEntity.setMenuPid(menuPid);
                menuEntity.setMenuType(1);
                menuEntity.setMenuName(tableEntity.getClassComment()+"管理");
                menuEntity.setMenuRouter("wen/modules/"+tableEntity.getModular()+"/views/"+tableEntity.getRoute()+"");
                menuEntity.setMenuViewPath("wen/modules/"+tableEntity.getModular()+"/views/"+tableEntity.getRoute()+".vue");
                menuEntityList.add(menuEntity);

                int resourcePid = MysqlUtils.tableId(datebaseEntity, "ums_resource", tableEntity.getModular()+"资源");
                if (resourcePid == 0){ // 没有上级菜单
                    resourceLastId = resourceLastId + 1;
                    ResourceEntity resourceEntity = new ResourceEntity();
                    resourceEntity.setResourceId(resourceLastId);
                    resourceEntity.setResourcePid(0);
                    resourceEntity.setResourceName(tableEntity.getModular()+"资源");
                    resourceEntity.setResourceUrl("/"+tableEntity.getModular()+"/"+tableEntity.getRoute()+"/*");
                    resourceEntity.setResourceNote(tableEntity.getClassComment()+"资源");
                    resourceEntity.setResourceWeb(tableEntity.getModular()+":"+tableEntity.getRoute());
                    resourceEntityList.add(resourceEntity);
                    resourcePid = resourceLastId;
                }
                for(int i = 0 ; i < resourceUrlStrs.length; i++){
                    ResourceEntity resourceEntity = new ResourceEntity();
                    resourceLastId = resourceLastId + 1;
                    resourceEntity.setResourceId(resourceLastId);
                    resourceEntity.setResourcePid(resourcePid);
                    resourceEntity.setResourceName(tableEntity.getClassComment()+resourceWebStrs[i]);
                    resourceEntity.setResourceUrl("/"+tableEntity.getModular()+"/"+tableEntity.getRoute()+"/"+resourceUrlStrs[i]);
                    resourceEntity.setResourceNote(tableEntity.getClassComment()+resourceWebStrs[i]);
                    resourceEntity.setResourceWeb(tableEntity.getModular()+":"+tableEntity.getRoute()+":"+resourceUrlStrs[i]);
                    resourceEntityList.add(resourceEntity);
                }
            }
            replaceMap.put("menuEntityList", menuEntityList);
            replaceMap.put("resourceEntityList", resourceEntityList);
            String vmfilePath = FileUtil.vmFilePath("Sql.vm", projectEntity);
            String stringWriter = VmUtils.render(replaceMap, vmfilePath);
            System.out.println(targetFile);
            writer(stringWriter, targetFile);
        }
    }
}
